import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_data_center/model/user_model.dart';
import 'package:flutter_data_center/net/dio_utils.dart';
// import 'package:flutter_data_center/screens/app/home_screen_backup.dart';
import 'package:flutter_data_center/screens/common/user_helper.dart';
import 'package:flutter_data_center/screens/config/config_screen.dart';
import 'package:flutter_data_center/screens/home/home_screen.dart';
import 'package:flutter_data_center/utills/log_utils.dart';
import 'package:flutter_data_center/utills/navigator_utils.dart';
import 'package:flutter_data_center/utills/toast_utils.dart';
import '../../../constants.dart';
import 'bg/bubble_widget.dart';
import 'components/custom_textfield_widget.dart';

class LoginScreen extends StatefulWidget {
  // final StreamController loginStreamController;
  LoginScreen();
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  // 密码输入框焦点控制
  FocusNode _passwordFocusNode = new FocusNode();
  // 手机号/用户名输入框焦点控制
  FocusNode _userNameFocusNode = new FocusNode();
  // 手机号输入框控制器
  TextEditingController _userNameEditController = new TextEditingController();
  // 密码输入框控制器
  TextEditingController _userPasswordEditController =
      new TextEditingController();
  // 是否显示密码
  bool _passwordShow = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          width: double.infinity,
          height: double.infinity,
          child: Stack(
            children: [
              //第一层 背景
              buildBackgroundWidget(),
              //第二层 气泡
              Positioned.fill(
                child: BubbleWidget(),
              ),
              //第三层 高斯模糊
              buildFliterWidget(),
              //第四层 logo
              buildLogoWidget(),
              // 第五层 输入框
              buildInputWidget(),
              // 第六层 关闭按钮
              // buildCloseWidget(),
            ],
          )),
    );
  }

  // 创建背景
  buildBackgroundWidget() {
    return Positioned.fill(
      child: Container(
        decoration: BoxDecoration(
          // 线性渐变
          gradient: LinearGradient(
              // 渐变开始方向
              begin: Alignment.topLeft,
              // 渐变结束方向
              end: Alignment.bottomRight,
              // 渐变的颜色组 至少有两个
              colors: [
                Colors.lightBlueAccent.withOpacity(0.3),
                Colors.blue.withOpacity(0.3),
              ]),
        ),
      ),
    );
  }

  // 创建高斯模糊
  buildFliterWidget() {
    return Positioned.fill(
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
        child: Container(
          color: Colors.white.withOpacity(0.3),
        ),
      ),
    );
  }

  // 创建logo
  buildLogoWidget() {
    return Positioned(
      top: 106,
      left: 60,
      right: 60,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            "登录",
            style: TextStyle(
              fontSize: 36,
              fontWeight: FontWeight.w700,
            ),
          ),
          Container(
            alignment: Alignment.center,
            width: 53,
            height: 22,
            margin: EdgeInsets.only(left: 25),
            decoration: BoxDecoration(
              color: primaryColor,
              borderRadius: BorderRadius.circular(50),
            ),
            child: Text(
              "1.0",
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white,
              ),
            ),
          ),
          // Hero(
          //   tag: "logo",
          //   child: Material(
          //     color: Colors.transparent,
          //     child: ClipOval(
          //       child: Image.asset("assets/images/app_icon.png",
          //           width: 33, height: 33),
          //     ),
          //   ),
          // ),
          // SizedBox(width: 20),
          // Text(
          //   "欢迎光临",
          //   style: TextStyle(
          //     fontWeight: FontWeight.w600,
          //     fontSize: 22,
          //     color: Colors.blue,
          //   ),
          // )
        ],
      ),
    );
  }

  // 构建关闭按钮
  buildCloseWidget() {
    return Positioned(
      left: 20,
      top: 20,
      child: CloseButton(
        color: Colors.white,
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  // 构建输入框与单选框
  buildInputWidget() {
    return Positioned(
      left: 30,
      right: 30,
      top: 222,
      child: Column(
        children: [
          //手机号
          TextFieldWidget(
            hintText: "手机号",
            submit: (value) {
              if (value.length != 11) {
                ToastUtils.showToast("请输入11位手机号");
                //手机号输入框重新获取焦点
                FocusScope.of(context).requestFocus(_userNameFocusNode);
                return;
              }
              //手机号输入框失去焦点
              _userNameFocusNode.unfocus();
              //密码输入框获取焦点
              FocusScope.of(context).requestFocus(_passwordFocusNode);
            },
            focusNode: _userNameFocusNode,
            prefixIconData: Icons.phone,
            controller: _userNameEditController,
            obscureText: false,
          ),
          SizedBox(
            height: 30,
          ),
          //密码

          TextFieldWidget(
            // 占位符
            hintText: "密码",
            // 提交事件
            submit: (value) {
              if (value.length < 6) {
                ToastUtils.showToast("请输入6位以上密码");
                //密码输入框获取焦点
                FocusScope.of(context).requestFocus(_passwordFocusNode);
                return;
              }
              //手机号输入框失去焦点
              _userNameFocusNode.unfocus();
              //密码输入框失去焦点
              _passwordFocusNode.unfocus();
            },
            // 焦点控制器
            focusNode: _passwordFocusNode,
            // 左侧图标占位
            prefixIconData: Icons.lock_open_outlined,
            // 右侧图标占位
            suffixIconData:
                _passwordShow ? Icons.visibility : Icons.visibility_off,
            // 是否显示右侧图标
            obscureText: _passwordShow,
            // 输入框控制器
            controller: _userPasswordEditController,
            // 右侧图标点击事件
            onTap: () {
              //设置密码输入框输入内容可见与不可见
              setState(() {
                _passwordShow = !_passwordShow;
              });
            },
          ),
          // 登录按钮
          SizedBox(height: 46),
          Container(
            height: 55,
            width: double.infinity,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(15),
              child: ElevatedButton(
                child: Text(
                  "登录",
                  style: TextStyle(
                    fontSize: 26,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  primary: Theme.of(context).primaryColor,
                ),
                onPressed: () {
                  LogUtils.e("点击了登录");
                  submitFunction();
                },
              ),
            ),
          ),
          SizedBox(height: 10),
          Center(
            child: IconButton(
                icon: Icon(Icons.settings),
                onPressed: () {
                  NavigatorUtils.pushPageByFade(
                    context: context,
                    targetPage: ConfigScreen(),
                    isReplace: false,
                  );
                }),
          ),
          // 注册按钮
          // SizedBox(height: 20),
          // Container(
          //   height: 44,
          //   width: double.infinity,
          //   child: ElevatedButton(
          //     child: Text("注册", style: TextStyle(fontSize: 18)),
          //     onPressed: () {
          //       LogUtils.e("点击了注册");
          //     },
          //   ),
          // ),
        ],
      ),
    );
  }

  ///登录功能
  void submitFunction() async {
    //获取用户名
    String userName = _userNameEditController.text;
    //获取密码
    String password = _userPasswordEditController.text;

    if (userName.trim().length != 11) {
      ToastUtils.showToast("请输入11位手机号");
      return;
    }
    if (password.trim().length < 6) {
      ToastUtils.showToast("请输入6位以上密码");
      return;
    }

    Map<String, dynamic> map = {
      "mobile": userName,
      "password": password,
      "nickName": "ggb",
      "avatarUrl":
          "https://images.pexels.com/photos/6969017/pexels-photo-6969017.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
    };

    //网络请求 发起 post 请求
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      //请求地址
      url: HttpHelper.login,
      //请求参数
      formDataMap: map,
    );
    if (responseInfo.success) {
      print(responseInfo.data["token"]);
      //解析数据
      UserModel userModel = UserModel.fromMap(responseInfo.data);
      //内存保存数据
      UserHelper.getInstance.userModel = userModel;
      //提示框
      ToastUtils.showToast("登录成功");
      //跳转到首页
      NavigatorUtils.pushPageByFade(
        context: context,
        targetPage: HomeScreen(),
        isReplace: true,
      );
    } else {
      //登录失败页面小提示
      ToastUtils.showToast("${responseInfo.msg}");
    }
  }
}
